/*
 * @Author       : 震雨 LuckRain7
 * @Date         : 2020-07-29
 * @Description  : axios 工具封装
 * @ Love and Peace
 */

// 引入axios模块
import axios from "axios";

// 引入路由组件进行跳转 
// 为跳转至404和登录页面
import router from "../router/index.js";

axios.defaults.headers.post["Content-Type"] =
    "application/x-www-form-urlencoded;charset=UTF-8";

// 创建实例
// timeout 配置过期时间
// withCredentials 是否接受 cookie
// headers 配置请求头
const service = axios.create({
    timeout: 1000 * 30,
    withCredentials: true,
    headers: {
        "Content-Type": "application/json; charset=utf-8",
        "Access-Control-Allow-Origin": "*",
    },
});

// 请求拦截
service.interceptors.request.use(
    config => {
        //加入对用户是否登录的判定，如果没有token那么返回登录页面进行登录，获取token，
        let userToken = localStorage.getItem("zhqh-pro-token");
        if (userToken == null) {
            this.$router.push("/login");
        }
        // 在请求头添加与服务端协商好的token字段
        config.headers['X-Access-Token'] = JSON.parse(localStorage.getItem('zhqh-pro-token'))
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截
// 401, token失效
service.interceptors.response.use(
    (response) => {
        if (response.data && response.data.code === 401) {
            localStorage.removeItem("zhqh-pro-token");
            router.push({ name: "login" });
        }
        if (response.data && response.data.code === 302) {
            router.push("/");
        }
        return response;
    },
    (error) => {
        if (error.status === 404) {
            router.push({ name: "404" });
        }
        return Promise.reject(error);
    }
);

// axios无权限限制 封装 HTTP 请求
// ----------------------------
// _get(url, potions, callback)
// *  description: 封装get请求
// *  param url {String}
// *  param potions {Object} 默认为{} 传入参数params参数
// *  return:  Promise
// *  ps: 根据约定 数据成功获取  success === true
class HTTP_UNLIMITED {

    // --- get请求 ---
    _get(url, options = {}) {
        return new Promise((resolve, reject) => {
            //console.log(options)
            axios
                .get(url, options)
                .then(function (response) {
                    const data = response.data
                    resolve(data)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }


    // --- post请求 ---
    _post(url, options = {}) {
        return new Promise((resolve, reject) => {
            axios
                .post(url, options)
                .then(function (response) {
                    const data = response.data
                    resolve(data)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }

    // --- put请求 ---
    _put(url, options = {}) {
        return new Promise((resolve, reject) => {
            axios
                .put(url, options)
                .then(function (response) {
                    const data = response.data
                    resolve(data)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }

    // --- delete 请求 ---
    _delete(url, options = {}) {
        return new Promise((resolve, reject) => {
            axios
                .delete(url, options)
                .then(function (response) {
                    const data = response.data
                    resolve(data)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }



}


// axios有权限 封装 HTTP 请求
// ----------------------------
// _get(url, potions, callback)
// *  description: 封装get请求
// *  param url {String}
// *  param potions {Object} 默认为{} 传入参数params参数
// *  return:  Promise
// *  ps: 根据约定 数据成功获取 success === true
class HTTP_LIMITED {
    // --- 导出excel ， 该请求的请求头不同，返回的是二进制文件  responseType: 'blob'  ---
    _exportExcel(url) {
        return axios({
            method: "get",
            url: url,
            responseType: 'blob',
            headers: {
                "X-Access-Token": JSON.parse(localStorage.getItem('zhqh-pro-token'))
            }
        })
    }

    // --- get请求 ---
    _get(url, options = {}) {
        return new Promise((resolve, reject) => {
            service
                .get(url, options)
                .then(function (response) {

                    const data = response.data
                    resolve(data)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }

    // --- post请求 ---
    _post(url, options = {}) {
        return new Promise((resolve, reject) => {
            service
                .post(url, options)
                .then(function (response) {
                    const data = response.data
                    resolve(data)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }

    // --- put请求 ---
    _put(url, options = {}) {
        return new Promise((resolve, reject) => {
            service
                .put(url, options)
                .then(function (response) {
                    const data = response.data
                    resolve(data)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }

    // --- delete 请求 ---
    _delete(url, options = {}) {
        return new Promise((resolve, reject) => {
            service
                .delete(url, options)
                .then(function (response) {
                    const data = response.data
                    resolve(data)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }

}

// 导出
export { service, HTTP_UNLIMITED, HTTP_LIMITED };
